import time
from load_config import load_dict_from_file

def connect_wifi(this_wifi):
    if this_wifi.isconnected():
        this_wifi.disconnect()
    
    wifi_setting = load_dict_from_file('config.json')
    if wifi_setting is {}:
        return (1, 'WIFI 未初始化！')
    # 连接网络
    this_wifi.connect(wifi_setting['SSID'], wifi_setting['PWD'])
    # 等待连接成功
    count = 0
    max_count = 10
    while not this_wifi.isconnected():
        count += 1
        print(f"{count}/10 正在连接...")
        time.sleep(1)
        if count >= max_count:
            this_wifi.disconnect()
            this_wifi.active(False)
            del this_wifi  # 删除对象引用
            return (1, 'connect time out !')
    return (0, this_wifi.ifconfig()[0])
